package world;

public class ChunkCache {
	private int chunkX;
	private int chunkZ;
	private Chunk[][] chunkArray;
	private boolean isEmpty;
	private World world;

	public ChunkCache(World world, int xl, int yl, int zl, int xh, int yh, int zh, int extSize) {
		this.world = world;
		this.chunkX = xl - extSize >> 4;
		this.chunkZ = zl - extSize >> 4;

		int l1 = xh + extSize >> 4;
		int i2 = zh + extSize >> 4;

		//include extension
		this.chunkArray = new Chunk[l1 - this.chunkX + 1][i2 - this.chunkZ + 1];
		for (int chunkXIndex = this.chunkX; chunkXIndex <= l1; ++chunkXIndex) {
			for (int chunkZIndex = this.chunkZ; chunkZIndex <= i2; ++chunkZIndex) {
				Chunk chunk = world.getChunkByChunkIndex(chunkXIndex, chunkZIndex);

				if (chunk != null) {
					this.chunkArray[chunkXIndex - this.chunkX][chunkZIndex - this.chunkZ] = chunk;
				}
			}
		}

		//do not include extension
		this.isEmpty = true;
		for (int chunkXIndex = xl >> 4; chunkXIndex <= xh >> 4; ++chunkXIndex) {
			for (int chunkZIndex = zl >> 4; chunkZIndex <= zh >> 4; ++chunkZIndex) {
				Chunk chunk = this.chunkArray[chunkXIndex - this.chunkX][chunkZIndex - this.chunkZ];

				if (chunk != null && !chunk.isAllSlicesEmpty(yl, yh)) {
					this.isEmpty = false;
				}
			}
		}
	}
	
	public boolean isEmpty() {
		return this.isEmpty;
	}
	
	public int getBlockId(int x, int y, int z) {
		if (y < 0) {
			return 0;
		} else if (y > 255) {
			return 0;
		} else {
			int l = (x >> 4) - this.chunkX;
			int i1 = (z >> 4) - this.chunkZ;

			if (l >= 0 && l < this.chunkArray.length && i1 >= 0 && i1 < this.chunkArray[l].length) {
				Chunk chunk = this.chunkArray[l][i1];
				return chunk == null ? 0 : chunk.getBlockID(x & 15, y, z & 15);
			} else {
				return 0;
			}
		}
	}

	public int getHeight() {
		return 256;
	}
}
